﻿package com.pro.ydl;

import java.util.Enumeration;
import java.util.Hashtable;

import com.pro.ydl.service.MainService;

import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface.OnKeyListener;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.View;
import android.view.Window;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.Toast;
import YDLControl.Control;
import android.view.MotionEvent;

public class UserLoginActivity extends Activity {

	private final Handler handle = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (progdialogLogin.isShowing()) {
				progdialogLogin.dismiss();
			}
			switch (msg.what) {
			case LOGIN_CHECK_ID: {
				if (0 == msg.arg1) {
					ShowToast(UserLoginActivity.this, "在线登录失败，请确认你的用户名和密码");
				} else {
					UserLoginActivity.this.finish();
					Intent intent = new Intent();
					intent.setClass(UserLoginActivity.this,
							MainHomeActivity.class);
					UserLoginActivity.this.startActivity(intent);

				}
			}
				break;
			}
		}
	};
	private static final int LOGIN_CHECK_ID = 1;
	private ProgressDialog progdialogLogin = null;

	@Override
	public void onDestroy() {
		// 减少计数
		Log.d("jiancheng", "onDestroy");
		YDLApplication YDLApplication = (YDLApplication) getApplication();
		YDLApplication.setDecreaseNum();
		super.onDestroy();
		
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.user_login_activity_layout);

		// 增加计数
		YDLApplication YDLApplication = (YDLApplication) getApplicationContext();
		YDLApplication.setAddNum();

		// set the button onTouch event
		ImageButton goBackBtn = (ImageButton) findViewById(R.id.btnImg_goback);
		goBackBtn.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.back_click));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.back));
				}
				return false;
			}
		});
		ImageButton submitBtn = (ImageButton) findViewById(R.id.btnImg_submit);
		submitBtn.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.submit_click));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.submit));
				}
				return false;
			}
		});
		ImageButton cancelBtn = (ImageButton) findViewById(R.id.btnImg_cancel);
		cancelBtn.setOnTouchListener(new View.OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				if (event.getAction() == MotionEvent.ACTION_DOWN) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.largecancel_click));
				} else if (event.getAction() == MotionEvent.ACTION_UP) {
					((ImageButton) v).setImageDrawable(getResources()
							.getDrawable(R.drawable.largecancel));
				}
				return false;
			}
		});
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		// getMenuInflater().inflate(R.menu.user_reg_activity_layout, menu);
		return true;
	}

	public void LoginFun(View view) {
		EditText userName, userPassword;
		String strUserName, strUserPassword;
		userName = (EditText) findViewById(R.id.userName);
		userPassword = (EditText) findViewById(R.id.userPassword);
		strUserName = userName.getText().toString();
		strUserPassword = userPassword.getText().toString();
		// hard code for test
		 //strUserName = "admin";
		 //strUserPassword = "seandai10";
		if(0 != strUserName.length()  && 0 != strUserPassword.length())
		{	
			if(false == isOnline())
			{
				OffLineLogin(strUserName,strUserPassword);
			}
			else
			{
				progdialogLogin = ProgressDialog.show(UserLoginActivity.this, "正在加载",
						"系统正在处理的 您请求");
				LoginThreadHandle(strUserName, strUserPassword);
			}
		}
		else
		{
			ShowToast(UserLoginActivity.this, "请输入用户和密码");
		}
	}

	public void emptyInput(View view) {
		EditText etUserName = (EditText) findViewById(R.id.userName);
		EditText etUserPassword = (EditText) findViewById(R.id.userPassword);
		etUserName.setText("");
		etUserPassword.setText("");
	}

	public void goToRegist(View view) {
		Intent intent = new Intent();
		intent.setClass(this, UserRegisterActivity.class);
		this.startActivity(intent);
	}

	public void goBack(View view) {
		UserLoginActivity.this.finish();
		Intent intent = new Intent();
		intent.setClass(this, MainHomeActivity.class);
		this.startActivity(intent);
	}

	public void ShowToast(Context context, String strShowMessage) {
		Toast toast = Toast.makeText(context, strShowMessage,
				Toast.LENGTH_SHORT);
		toast.setGravity(Gravity.CENTER, 0, 0);
		toast.show();
	}

	public void goFoundSerect(View view) {
		Intent intent = new Intent();
		intent.setAction("android.intent.action.VIEW");
		Uri content_url = Uri
				.parse("http://www.yundongling.com/pub/ForgotPassword.aspx");
		intent.setData(content_url);
		startActivity(intent);
	}

	public void LoginThreadHandle(final String name, final String serect) {
		new Thread() {
			@Override
			public void run() {
				Control callDatabase = new Control();
				Message msg = new Message();
				msg.what = LOGIN_CHECK_ID;
				Enumeration e;
				Hashtable<String, Object> loginState = new Hashtable<String, Object>();
				String sUserId;
				try {
					loginState = callDatabase.myLogin(name, serect, "1",
							UserLoginActivity.this);
				} catch (Exception ex) {
					Log.e("UserLoginActivity", "登入异常");
				}
				e = loginState.keys();
				String a = loginState.get("sessionID").toString();
				String b = loginState.get("userID").toString();
				if (e.hasMoreElements()) {
					if (loginState.get("sessionID").toString().equals("error")) {
						msg.arg1 = 0;
					} else {
						if (name.equals("admin")) {
							sUserId = "7";
						} else {
							sUserId = loginState.get("userID").toString();
						}
						String sSession = loginState.get("sessionID")
								.toString();
						SharedPreferences sharedPreferences = UserLoginActivity.this
								.getSharedPreferences("YDL",
										Context.MODE_PRIVATE);
						Editor editor = sharedPreferences.edit();
						editor.putString("sUserID", sUserId);
						editor.putBoolean("bCurrentRegisterSts", true);
						editor.putString("sSession", sSession);
						editor.putString("sUserName", name);
						editor.putString("sUserPassword", serect);
						editor.commit();
						msg.arg1 = 1;

					}
				} else {
					msg.arg1 = 0;
				}
				handle.sendMessage(msg);
			}
		}.start();
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		final YDLApplication YDLApplication = (YDLApplication) getApplication();
		if (KeyEvent.KEYCODE_BACK == keyCode) {
			System.out.println("YDLApplication.getNum() ="
					+ YDLApplication.getNum());
			if (YDLApplication.getNum() <= 1) {
				// 退出APP
				AlertDialog.Builder builder = new Builder(this);
				builder.setTitle("提示");
				builder.setMessage("是否退出?");
				builder.setPositiveButton("确定",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								Log.d("jiancheng",
										"onClick(DialogInterface arg0, int arg1)");
								System.exit(0);
							}
						});
				builder.setNegativeButton("取消",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								// TODO Auto-generated method stub
								arg0.dismiss();
							}
						});
				builder.create().show();
				return true;
			} else {
				Log.d("jiancheng", "UserLoginActivity.this.finish();");
				UserLoginActivity.this.finish();
				return false;
			}
			
		} else {

			return true;
		}

	}

	private Boolean isOnline() {
		ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo ni = cm.getActiveNetworkInfo();
		if (ni != null && ni.isConnected()) {
			return true;
		}
		return false;
	}
	private void OffLineLogin(String strUserName,String strUserPassword)
	{
		int iUserID = 0;
		iUserID = new Control().loginLocal(strUserName,strUserPassword,UserLoginActivity.this);	
		if(0 == iUserID)
		{
			ShowToast(UserLoginActivity.this, "离线登录失败，请确认你的用户名和密码");
		}
		else
		{
			SharedPreferences sharedPreferences = UserLoginActivity.this
					.getSharedPreferences("YDL",
							Context.MODE_PRIVATE);
			Editor editor = sharedPreferences.edit();
			editor.putString("sUserID", Integer.toString(iUserID));
			editor.putBoolean("bCurrentRegisterSts", true);
			//editor.putString("sSession", sSession);
			editor.putString("sUserName", strUserName);
			editor.putString("sUserPassword", strUserPassword);
			editor.commit();
			
			UserLoginActivity.this.finish();
			Intent intent = new Intent();
			intent.setClass(UserLoginActivity.this,
					MainHomeActivity.class);
			UserLoginActivity.this.startActivity(intent);	
		}
	}

}
